package cn.ms.doctor.Interceptor;

import cn.ms.doctor.Entity.User;
import cn.ms.doctor.Resolver.GetSessionUserInter;
import cn.ms.doctor.Utils.DataStandardUtils;
import cn.ms.doctor.Utils.GlobalMessage;
import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class isLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json");
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("userMsg");
        System.out.println(user);
        String requestURI = request.getRequestURI();
        if(DataStandardUtils.isPattern("/isLogin/",requestURI)){
            String error="出现异常";
            if (user==null){
                error="请登陆后操作...";
            }else if (DataStandardUtils.isPattern("/isSystemAdmin/",requestURI)&&user.getRoleId()!=1){
                error="请使用管理员账号登录...";
            }else if (DataStandardUtils.isPattern("/isDrugs/",requestURI)&&user.getRoleId()!=2){
                error="请使用药物管理员账号登录...";
            }else if (DataStandardUtils.isPattern("/isDoctor/",requestURI)&&user.getRoleId()!=3){
                error="请使用医生账号登录...";
            }else if (DataStandardUtils.isPattern("/isSystemAndDrugs/",requestURI)&&user.getRoleId()==3){
                error="请使用系统管理员或者药物管理员账号登录...";
            }else if (DataStandardUtils.isPattern("/isSystemAndDoctor/",requestURI)&&user.getRoleId()==2){
                System.out.println(requestURI);
                System.out.println(user.getRoleId()!=1&&user.getRoleId()!=3);

                error="请使用系统管理员或者医生账号登录...";
            }else {
                System.out.println(requestURI);
                return true;
            }
            response.getWriter().print(JSON.toJSONString(new GlobalMessage(401,3,error,null)));
            return false;
        }else if (DataStandardUtils.isPattern("/NotLogin/",requestURI)){
            if (user!=null){

                response.getWriter().print(JSON.toJSONString(new GlobalMessage(401,3,"当前url需要退出登录才允许访问",null)));
                return false;
            }

        }
        return true;
    }
}
